package com.qzsoft.zhjd.asphalt.modules.asphaltmatch.service.impl;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.dto.AsphaltMatchSieveDto;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.dto.AsphaltMatchTypeListDto;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.dto.AsphaltMatchTypeSelectDto;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.entity.AsphaltMatchNameEntity;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.entity.AsphaltMatchTypeEntity;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.mapper.AsphaltMatchTypeMapper;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.service.AsphaltMatchNameService;
import com.qzsoft.zhjd.asphalt.modules.asphaltmatch.service.AsphaltMatchTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qzsoft.zhjd.common.components.BaseServiceComponent;
import com.qzsoft.zhjd.common.enums.BizCode;
import com.qzsoft.zhjd.common.utils.RenExceptionUtils;


/**
 * @ClassName AsphaltMatchTypeServiceImpl
 * @Description 级配类型业务接口实现
 * @author linhuawei
 * @since 2021-11-22
 */
@Service
public class AsphaltMatchTypeServiceImpl extends ServiceImpl<AsphaltMatchTypeMapper, AsphaltMatchTypeEntity>
        implements AsphaltMatchTypeService {

    @Autowired
    private BaseServiceComponent baseServiceComponent;

    @Autowired
    private AsphaltMatchNameService asphaltMatchNameService;

    @Override
    public IPage<AsphaltMatchTypeListDto> pageDto(Map<String, Object> params) {
        IPage<AsphaltMatchTypeListDto> page = baseServiceComponent.getPage(params, AsphaltMatchTypeListDto.class);
        return baseMapper.queryDto(page, params);
    }

    @Override
    public List<AsphaltMatchTypeSelectDto> listSelect(Map<String, Object> params) {
        return baseMapper.listSelect(params);
    }

    @Override
    public AsphaltMatchTypeEntity getByType(String type) {
        if(ObjectUtils.isEmpty(type)) {
            return null;
        }
        QueryWrapper<AsphaltMatchTypeEntity> queryWrapper = new QueryWrapper<AsphaltMatchTypeEntity>();
        queryWrapper.like("type", type);
        List<AsphaltMatchTypeEntity> list = baseMapper.selectList(queryWrapper);
        return null == list || 0 == list.size() ? null : list.get(0);
    }


    @Override
    public List<AsphaltMatchSieveDto> getSieveArray(String matchType) {
        // 获取级配类型信息
        AsphaltMatchTypeEntity matchTypeEntity = null;
        if (ObjectUtils.isNotEmpty(matchType)) {
            matchTypeEntity = getByType(matchType);
        }
        if (null == matchTypeEntity || null == matchTypeEntity.getSieveArray()) {
            return new ArrayList<AsphaltMatchSieveDto>();
        }

        // 处理级配类型筛孔数据
        JSONArray array = matchTypeEntity.getSieveArray();
        List<AsphaltMatchSieveDto> list = new ArrayList<AsphaltMatchSieveDto>();
        AsphaltMatchSieveDto dto;
        BigDecimal size;
        String code;
        for (int i = 0, len = array.size(); i < len; i++) {
            try {
                size = array.getBigDecimal(i);
                code = size.toString().replace(".", "d");

                dto = new AsphaltMatchSieveDto();
                dto.setCode(code);
                dto.setSize(size);
                list.add(dto);
            } catch (Exception e) {
            }
        }

        return list;
    }

    @Override
    public boolean save(AsphaltMatchTypeEntity entity) {
        // 判断类型是否存在
        QueryWrapper<AsphaltMatchTypeEntity> queryWrapper = new QueryWrapper<AsphaltMatchTypeEntity>();
        queryWrapper.eq("type", entity.getType());
        Integer count = baseMapper.selectCount(queryWrapper);
        if (null != count && 0 < count) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "级配类型[" + entity.getType() + "]已经存在");
        }

        handlerSieve(entity);
        return super.save(entity);
    }

    @Override
    public boolean updateById(AsphaltMatchTypeEntity entity) {
        handlerSieve(entity);
        return super.updateById(entity);
    }

    @Override
    public boolean removeById(Serializable id) {
        // 获取当前级配类型
        AsphaltMatchTypeEntity entity = baseMapper.selectById(id);
        if(null == entity) {
            return true;
        }

        // 判断当前级配类型是否在用
        QueryWrapper<AsphaltMatchNameEntity> queryWrapper = new QueryWrapper<AsphaltMatchNameEntity>();
        queryWrapper.eq("type", entity.getType());
        Integer count = asphaltMatchNameService.count(queryWrapper);
        if(null != count && 0 < count) {
            RenExceptionUtils.throwEx(BizCode.PARAMS_ERROR, "当前级配类型正在使用，不可删除");
        }

        return super.removeById(id);
    }

    /**
     * @Title handlerSieve
     * @Description 梳理筛孔数据
     * @param entity 级配类型数据
     */
    private void handlerSieve(AsphaltMatchTypeEntity entity) {
        // 判断是否为空
        JSONArray sieveArray = entity.getSieveArray();
        if (null == sieveArray || 0 == sieveArray.size()) {
            return;
        }

        // 获取筛孔数据
        List<BigDecimal> list = new ArrayList<BigDecimal>();
        for (int i = 0, len = sieveArray.size(); i < len; i++) {
            try {
                list.add(sieveArray.getBigDecimal(i));
            } catch (Exception e) {
            }
        }
        if (null == list || 0 == list.size()) {
            return;
        }

        // 筛孔数据排序
        list.sort(new Comparator<BigDecimal>() {
            public int compare(BigDecimal o1, BigDecimal o2) {
                return o1.compareTo(o2);
            };
        });

        // 返回结果数据
        sieveArray = new JSONArray(list.size());
        for (BigDecimal val : list) {
            sieveArray.add(val);
        }

        // 设置最大筛孔
        BigDecimal maxSieveSize = null;
        BigDecimal nominalMaxSieveSize = null;
        if (null != sieveArray && 0 < sieveArray.size()) {
            // 获取最后一条数据作为最大筛孔
            int size = sieveArray.size() - 1;
            maxSieveSize = sieveArray.getBigDecimal(size);

            // 倒数第二条数据作为公称最大筛孔
            // 如果只有一个筛孔，公称最大筛孔 = 最大筛孔
            size = 0 == size ? size : size - 1;
            nominalMaxSieveSize = sieveArray.getBigDecimal(size);
        }
        entity.setSieveArray(sieveArray);
        entity.setMaxSieveSize(maxSieveSize);
        entity.setNominalMaxSieveSize(nominalMaxSieveSize);
    }

}
